# MODS: Model Summary and Fit Measures

mod_summary <- function(object) {
  
  fits <- data.frame(t( 
    
    sapply(object, function(mod) {
      sum <- summary(mod)    
      c(
        df = sum$df[1],
        adjR2 = sum$adj.r.squared, 
        Deviance = extractAIC(mod, k=0)[2],
        AIC = extractAIC(mod)[2],
        BIC = extractAIC(mod, k=log(2000))[2]
      )
      
      
      
    })
  ))
  fits$model <- factor(names(object))
  rownames(fits) <- paste("m", fits$model, sep="")
  fits
}


## COEFS:  Extract Coefficients and Uncertainties 

coef_simple <- function(object){
  coefs <- data.frame( 
    variable = rownames(summary(object)$coefficients)[-1],
    Est = summary(object)$coefficients[-1, 1],
    SE = summary(object)$coefficients[-1, 2]
  )

  coefs
}


coef_summary <- function(object) {
  
  coefs <- lapply(object, coef_simple)
  
  rows <- unlist(lapply(coefs, .row_names_info))
  rows <- abs(as.vector(rows))
  mnr <- as.vector(as.integer(names(object)))
  
  model.vec <- rep(1, rows[1])
  for(i in mnr[-1]){
    model.vec <- c(model.vec, rep(i, rows[i]))
  }
  
  coefs <- do.call(rbind, lapply(coefs, data.frame))
  coefs$model <- model.vec
  coefs$model <- factor(coefs$model)
  
  all <- expand.grid(
    model = unique(coefs$model),
    variable = unique(coefs$variable))
  
  coefs <- merge(all, coefs, by = c("model", "variable"), all.x=T)
  
  rownames(coefs) <- paste("m", coefs$model, "v", as.numeric(coefs$variable),
                           sep = "")
  
  coefs
}




